from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from typing import Optional
from module_user.entity.do.bg_affiliate_relation_do import BgAffiliateRelation
from datetime import datetime


class BgAffiliateRelationDao:
    """推广关系DAO"""

    async def get_by_invitee_id(self, db: AsyncSession, invitee_id: int) -> Optional[BgAffiliateRelation]:
        """根据被邀请人ID获取推广关系"""
        result = await db.execute(
            select(BgAffiliateRelation).filter(
                BgAffiliateRelation.invitee_id == invitee_id
            )
        )
        return result.scalar_one_or_none()

    async def create_relation(self, db: AsyncSession, inviter_id: int, invitee_id: int, affiliate_code: str) -> BgAffiliateRelation:
        """创建推广关系"""
        relation = BgAffiliateRelation(
            inviter_id=inviter_id,
            invitee_id=invitee_id,
            affiliate_code=affiliate_code,
            invite_time=datetime.now(),
            status=1
        )
        db.add(relation)
        await db.commit()
        await db.refresh(relation)
        return relation

    async def is_invitee_exists(self, db: AsyncSession, invitee_id: int) -> bool:
        """检查被邀请人是否已存在推广关系"""
        result = await db.execute(
            select(BgAffiliateRelation).filter(
                BgAffiliateRelation.invitee_id == invitee_id
            )
        )
        return result.scalar_one_or_none() is not None
